const express = require('express');
const router = express.Router();
const el_user_book = require('../../models/el_user_book');
const el_qu = require('../../models/el_qu');
const el_paper = require('../../models/el_paper');
const el_paper_qu = require('../../models/el_paper_qu');
const el_paper_qu_answer = require('../../models/el_paper_qu_answer');
const { generate19DigitId } = require('../../utils/idUtils');

// 查询el_user_book表并统计错误次数，完成后新增记录
router.post('/user/wrong-book/paging', async (req, res) => {
    try {
        const { current, size } = req.body
        const { examId, userId, title } = req.body.params

        // 1. 先检查数据库中是否已存在该examID对应的记录
        const existingRecords = await el_user_book.findUserBookByUserIdAndExamId(userId, examId, 1, 1)

        // 如果已存在记录，直接返回分页数据
        if (existingRecords && existingRecords.length > 0) {
            // 查询分页数据
            let recordsRes = await el_user_book.findUserBookByUserIdAndExamId(userId, examId, current, size)
            recordsRes = recordsRes.filter(item => item.wrong_count > 0)

            // 2. 检查是否有查询标题
            if (title) {
                recordsRes = recordsRes.filter(item => item.title.includes(title))
            }

            const records = recordsRes.map(item => ({
                "id": item.id,
                "examId": item.exam_id,
                "userId": item.user_id,
                "quId": item.qu_id,
                "createTime": item.create_time,
                "updateTime": item.update_time,
                "wrongCount": item.wrong_count,
                "title": item.title,
                "sort": item.sort
            })).sort((a, b) => b.wrongCount - a.wrongCount)

            // 查询总记录数用于分页计算
            let totalRecords = await el_user_book.findUserBookByUserIdAndExamId(userId, examId, 1, 1000)

            // 2. 检查是否有查询标题
            if (title) {
                totalRecords = totalRecords.filter(item => item.title.includes(title))
            }

            return res.json({
                msg: "操作成功！",
                code: 0,
                data: {
                    records: records,
                    total: totalRecords.filter(item => item.wrong_count > 0).length,
                    size: size,
                    current: current,
                    orders: [],
                    optimizeCountSql: true,
                    hitCount: false,
                    searchCount: true,
                    pages: Math.ceil(totalRecords.length / size)
                },
                success: true
            });
        }

        // 2. 如果不存在记录，则进行统计和新增
        // 通过examId和userId查询用户的所有试卷
        const papers = await el_paper.findPaperByExamIdAndUserId(examId, userId)
        const paperIds = papers.map(item => item.id)

        // 3. 统计每道题目的错误次数并新增记录
        // 通过试卷id查询所有题目id
        const quIdsResult = []
        for (const paperId of paperIds) {
            const quIds = await el_paper_qu.findPaperQuByPaperIdAndIsUserDelete(paperId, 0)
            quIdsResult.push(...quIds)
        }

        // 统计每道题目的错误次数并新增记录
        const currentTime = new Date()
        const newRecords = []

        //统计quIdsResult中每个元素的qu_id字段的出现次数
        const quIdCounts = quIdsResult.reduce((acc, item) => {
            // 这里item是包含qu_id字段的对象，需要提取qu_id
            const quId = item.qu_id;
            acc[quId] = (acc[quId]) + item.is_right === 0 ? 1 : 0
            return acc;
        }, {})

        // 查看统计结果
        // console.log('题目ID统计结果:', JSON.stringify(quIdCounts, null, 2))

        // 筛选出有错误次数的题目ID
        const wrongQuIds = Object.keys(quIdCounts).filter(quId => quIdCounts[quId] > 0)

        // 查看统计结果
        // console.log('错误题目ID列表:', wrongQuIds)

        //el_user_book新增记录
        for (const quId of wrongQuIds) {
            // 查询该题目的详细信息
            const quInfo = await el_qu.findQuById(quId)
            if (!quInfo) continue

            // 构建新增记录
            const record = {
                id: generate19DigitId(),
                exam_id: examId,
                user_id: userId,
                qu_id: quId,
                create_time: currentTime,
                update_time: currentTime,
                wrong_count: quIdCounts[quId],
                title: quInfo.content,
                sort: newRecords.length + 1 // sort，按新增顺序排序
            }
            newRecords.push(record)
            // 新增记录到数据库
            await el_user_book.addUserBook(record)
        }

        // 3. 新增完成后，查询分页数据返回
        const recordsRes = await el_user_book.findUserBookByUserIdAndExamId(userId, examId, current, size);

        const records = recordsRes.map(item => ({
            "id": item.id,
            "examId": item.exam_id,
            "userId": item.user_id,
            "quId": item.qu_id,
            "createTime": item.create_time,
            "updateTime": item.update_time,
            "wrongCount": item.wrong_count,
            "title": item.title,
            "sort": item.sort
        })).sort((a, b) => b.wrongCount - a.wrongCount)


        // 查询总记录数用于分页计算
        const totalRecords = await el_user_book.findUserBookByUserIdAndExamId(userId, examId, 1, 1000);
        return res.json({
            msg: "操作成功！",
            code: 0,
            data: {
                records: records,
                total: totalRecords.filter(item => item.wrong_count > 0).length,
                size: size,
                current: current,
                orders: [],
                optimizeCountSql: true,
                hitCount: false,
                searchCount: true,
                pages: Math.ceil(totalRecords.length / size)
            },
            success: true
        });
    } catch (error) {
        console.error('数据库操作错误', error)
        return res.status(500).json({
            msg: 'Internal server error',
            code: 500,
            success: false
        })
    }
})



router.post('/user/wrong-book/next', async (req, res) => {
    try {
        const { examId, quId, userId } = req.body;

        // 查询用户在该考试中的所有错题记录
        const result = await el_user_book.findUserBookByUserIdAndExamId(userId, examId)

        if (!result || result.length === 0) {
            return res.json({
                msg: "该用户在该考试中没有错题记录！",
                code: 404,
                success: false
            })
        }

        // 按sort字段排序，确保题目顺序正确
        const sortedRecords = result.sort((a, b) => a.sort - b.sort)

        // 查找当前题目在列表中的位置
        const currentIndex = sortedRecords.findIndex(item => item.qu_id === quId)

        let nextQuId = null;
        let nextTitle = null;

        if (currentIndex !== -1) {
            // 如果找到当前题目，获取下一题
            const nextIndex = (currentIndex + 1) % sortedRecords.length // 循环到第一题
            nextQuId = sortedRecords[nextIndex].qu_id
            nextTitle = sortedRecords[nextIndex].title
        } else {
            // 如果没找到当前题目，返回第一题
            nextQuId = sortedRecords[0].qu_id
            nextTitle = sortedRecords[0].title
        }

        return res.json({
            msg: "操作成功！",
            code: 0,
            data: {
                id: nextQuId,
            },
            success: true
        });
    } catch (error) {
        console.error('数据库操作错误', error);
        res.json({
            msg: 'Internal server error',
            code: 500,
            success: false
        })
    }
})

router.post('/user/wrong-book/delete', async (req, res) => {
    try {
        //这个接口现在出现，删除后，会把答题记录也删除，影响paper-result

        const { ids } = req.body

        // 循环删除每个错题本
        for (const id of ids) {
            const userBook = await el_user_book.findUserBookById(id)

            const { exam_id, qu_id, user_id } = userBook[0]

            //根据exam_id查询el_paper关联的所有试卷
            const papers = await el_paper.findPaperByExamIdAndUserId(exam_id, user_id)

            //根据paperIds删除el_paper_qu_answer表中相关记录
            for (const paper of papers) {
                //把el_paper_qu中is_user_delete字段更新为1
                await el_paper_qu.updateIsUserDelete(paper.id, qu_id, 1)
            }
            await el_user_book.deleteUserBook(id)
        }

        return res.json({
            "msg": "请求成功！",
            "code": 0,
            "success": true
        })
    } catch (error) {
        console.error('数据库操作错误', error);
        return res.status(500).json({
            msg: 'Internal server error',
            code: 500,
            success: false
        })
    }
})

router.post('/monitor/online/list', async (req, res) => {
    try {
        //获取在线用户的ip地址，登录地点，操作系统
        console.log('请求')
        // 从请求头中提取User-Agent信息
        const userAgent = req.headers['user-agent'] || '';

        // 解析操作系统信息
        const getOperatingSystem = (ua) => {
            console.log('User-Agent:', ua)
            if (ua.includes('Windows')) return 'Windows';
            if (ua.includes('Mac')) return 'macOS';
            if (ua.includes('Linux')) return 'Linux';
            if (ua.includes('Android')) return 'Android';
            if (ua.includes('iOS') || ua.includes('iPhone') || ua.includes('iPad')) return 'iOS';
            return 'Unknown';
        }

        // 解析浏览器信息
        const getBrowser = (ua) => {
            if (ua.includes('Chrome')) return 'Chrome';
            if (ua.includes('Firefox')) return 'Firefox';
            if (ua.includes('Safari') && !ua.includes('Chrome')) return 'Safari';
            if (ua.includes('Edge')) return 'Edge';
            if (ua.includes('Opera')) return 'Opera';
            return 'Unknown';
        };

        // 获取IP地址（考虑代理情况）
        const getClientIP = (req) => {
            return req.headers['x-forwarded-for'] ||
                req.headers['x-real-ip'] ||
                req.connection.remoteAddress ||
                req.socket.remoteAddress ||
                req.connection.socket?.remoteAddress ||
                'Unknown';
        };

        // 根据IP地址推断地理位置（简化版，实际项目中可以使用第三方API）
        const getLocationByIP = (ip) => {
            // 这里可以集成第三方IP地理位置查询服务
            // 目前返回简单的地理位置推断
            if (ip === '127.0.0.1' || ip === '::1') return '本地';
            if (ip.includes('192.168.') || ip.includes('10.') || ip.includes('172.')) return '内网';
            return '外网';
        };

        const clientIP = getClientIP(req);
        const os = getOperatingSystem(userAgent)
        const browser = getBrowser(userAgent);
        const location = getLocationByIP(clientIP);


        // 解析操作系统信息
        console.log('操作系统:', os)


        // 构建在线用户信息
        const onlineUserInfo = {
            // 基本信息
            ip: clientIP,
            remoteAddress: req.socket.remoteAddress,
            location: location,
            accessTime: new Date().toISOString(),

            // 设备信息
            operatingSystem: os,
            browser: browser,
            userAgent: userAgent,

            // 请求信息
            method: req.method,
            url: req.url,
            host: req.headers['host'],

            // 其他有用信息
            acceptLanguage: req.headers['accept-language'],
            acceptEncoding: req.headers['accept-encoding'],
            contentType: req.headers['content-type']
        };

        return res.json({
            msg: "操作成功！",
            code: 0,
            data: onlineUserInfo,
            success: true
        });
    } catch (error) {
        console.error('数据库操作错误', error);
        return res.json({
            msg: 'Internal server error',
            code: 500,
            success: false
        })
    }
})

module.exports = router;